import { Request, Response, NextFunction } from 'express';
import { Circle, User } from '../models';
import InterestTag from '../models/InterestTag';
import { CirclePost } from '../models/CirclePost';
import { Op } from 'sequelize';
import { sequelize } from '../config/database';
import { AppError } from '../utils/errorHandler';

// 创建圈子
export const createCircle = async (req: Request, res: Response): Promise<void> => {
    try {
        const { name, description, coverImage, tags } = req.body;
        const userId = req.user?.id;
        if (!userId) {
            res.status(401).json({ message: '未授权' });
            return;
        }
        const result = await sequelize.transaction(async (t) => {
            const circle = await Circle.create({ name, description, coverImage, creatorId: userId, memberCount: 1 }, { transaction: t });
            if (tags && tags.length > 0) {
                await circle.setTags(tags, { transaction: t });
            }
            await circle.addMember(userId, { through: { role: 'admin', status: 'active' }, transaction: t });
            return circle;
        });
        res.status(201).json(result);
        return;
    } catch (error) {
        console.error('创建圈子失败:', error);
        res.status(500).json({ message: '创建圈子失败' });
        return;
    }
};

// 获取圈子列表
export const getCircles = async (req: Request, res: Response): Promise<void> => {
    console.log('Received GET /api/circles request');
    try {
        const { page = 1, limit = 10, tagId, search } = req.query;
        const offset = (Number(page) - 1) * Number(limit);

        const where: any = {};
        if (tagId) {
            where['$tags.id$'] = tagId;
        }
        if (search) {
            where[Op.or] = [
                { name: { [Op.like]: `%${search}%` } },
                { description: { [Op.like]: `%${search}%` } }
            ];
        }

        const { count, rows } = await Circle.findAndCountAll({
            where,
            include: [
                {
                    model: User,
                    as: 'creator',
                    attributes: ['id', 'username', 'avatar'],
                },
                {
                    model: InterestTag,
                    as: 'tags',
                    attributes: ['id', 'name'],
                },
            ],
            limit: Number(limit),
            offset,
            order: [['createdAt', 'DESC']]
        });

        res.json({
            total: count,
            pages: Math.ceil(count / Number(limit)),
            currentPage: Number(page),
            circles: rows
        });
        return;
    } catch (error) {
        console.error('获取圈子列表失败:', error);
        res.status(500).json({ message: '获取圈子列表失败' });
        return;
    }
};

// 获取圈子详情
export const getCircleDetail = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const circle = await Circle.findByPk(id, {
            include: [
                {
                    model: User,
                    as: 'creator',
                    attributes: ['id', 'username', 'avatar'],
                },
                {
                    model: InterestTag,
                    as: 'tags',
                    attributes: ['id', 'name'],
                },
                {
                    model: User,
                    as: 'members',
                    attributes: ['id', 'username', 'avatar'],
                    through: {
                        attributes: ['role', 'status'],
                    },
                },
            ],
        });

        if (!circle) {
            throw new AppError('圈子不存在', 404);
        }

        res.json(circle);
        return;
    } catch (error) {
        console.error('获取圈子详情失败:', error);
        res.status(500).json({ message: '获取圈子详情失败' });
        return;
    }
};

// 更新圈子信息
export const updateCircle = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const { name, description, coverImage, isPrivate, tagIds } = req.body;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        const circle = await Circle.findByPk(id);
        if (!circle) {
            throw new AppError('圈子不存在', 404);
        }

        if (circle.creatorId !== userId) {
            throw new AppError('无权修改此圈子', 403);
        }

        // 如果修改了名称，检查是否已存在
        if (name && name !== circle.name) {
            const existingCircle = await Circle.findOne({ where: { name } });
            if (existingCircle) {
                throw new AppError('圈子名称已存在', 400);
            }
        }

        const result = await sequelize.transaction(async (t) => {
            // 更新圈子信息
            await circle.update({
                name,
                description,
                coverImage,
                isPrivate
            }, { transaction: t });

            // 更新标签
            if (tagIds) {
                await circle.setTags(tagIds, { transaction: t });
            }

            // 获取更新后的完整信息
            const updatedCircle = await Circle.findByPk(id, {
                include: [
                    {
                        model: User,
                        as: 'members',
                        attributes: ['id', 'username', 'avatar']
                    },
                    {
                        model: InterestTag,
                        as: 'tags',
                        attributes: ['id', 'name']
                    }
                ]
            });

            return updatedCircle;
        });

        res.json(result);
        return;
    } catch (error) {
        console.error('更新圈子信息失败:', error);
        res.status(500).json({ message: '更新圈子信息失败' });
        return;
    }
};

// 删除圈子
export const deleteCircle = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        const circle = await Circle.findByPk(id);
        if (!circle) {
            throw new AppError('圈子不存在', 404);
        }

        if (circle.creatorId !== userId) {
            throw new AppError('无权删除此圈子', 403);
        }

        await circle.destroy();
        res.json({ message: '圈子删除成功' });
        return;
    } catch (error) {
        console.error('删除圈子失败:', error);
        res.status(500).json({ message: '删除圈子失败' });
    }
};

// 加入圈子
export const joinCircle = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        const circle = await Circle.findByPk(id);
        if (!circle) {
            throw new AppError('圈子不存在', 404);
        }

        // 检查是否已经是成员
        const isMember = await circle.hasMember(userId);
        if (isMember) {
            throw new AppError('已经是圈子成员', 400);
        }

        await circle.addMember(userId, {
            through: { role: 'member', status: 'active' }
        });

        // 更新成员数量
        await circle.increment('memberCount');

        res.json({ message: '成功加入圈子' });
        return;
    } catch (error) {
        console.error('加入圈子失败:', error);
        res.status(500).json({ message: '加入圈子失败' });
    }
};

// 退出圈子
export const leaveCircle = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        const circle = await Circle.findByPk(id);
        if (!circle) {
            throw new AppError('圈子不存在', 404);
        }

        // 检查是否是成员
        const isMember = await circle.hasMember(userId);
        if (!isMember) {
            throw new AppError('不是圈子成员', 400);
        }

        // 检查是否是创建者
        if (circle.creatorId === userId) {
            throw new AppError('圈子创建者不能退出圈子', 400);
        }

        await circle.removeMember(userId);

        // 更新成员数量
        await circle.decrement('memberCount');

        res.json({ message: '成功退出圈子' });
        return;
    } catch (error) {
        console.error('退出圈子失败:', error);
        res.status(500).json({ message: '退出圈子失败' });
    }
};

// 获取圈子成员列表
export const getCircleMembers = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const { page = 1, limit = 20 } = req.query;
        const offset = (Number(page) - 1) * Number(limit);

        const circle = await Circle.findByPk(id);
        if (!circle) {
            throw new AppError('圈子不存在', 404);
        }

        const members = await circle.getMembers({
            attributes: ['id', 'username', 'avatar'],
            through: {
                attributes: ['role', 'status', 'createdAt']
            },
            limit: Number(limit),
            offset,
            order: [
                [{ model: User, as: 'members' }, 'createdAt', 'ASC']
            ]
        });

        const total = await circle.countMembers();

        res.json({
            total,
            pages: Math.ceil(total / Number(limit)),
            currentPage: Number(page),
            members
        });
        return;
    } catch (error) {
        console.error('获取圈子成员失败:', error);
        res.status(500).json({ message: '获取圈子成员失败' });
    }
};

// 更新圈子成员
export const updateCircleMember = async (req: Request, res: Response): Promise<void> => {
    try {
        const { circleId, targetUserId } = req.params;
        const { role, status } = req.body;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        const circle = await Circle.findByPk(circleId, {
            include: [
                {
                    model: User,
                    as: 'members',
                    where: { id: userId },
                    through: {
                        attributes: ['role'],
                    },
                },
            ],
        });

        if (!circle) {
            throw new AppError('圈子不存在', 404);
        }

        const members: any[] = (circle as any).members;
        const userRole = members && members[0]?.CircleMember?.role;
        if (!userRole || !['admin', 'moderator'].includes(userRole)) {
            throw new AppError('权限不足', 403);
        }

        const [member] = await circle.getMembers({ where: { id: targetUserId } });
        if (!member) {
            throw new AppError('成员不存在', 404);
        }

        const memberThrough = member.get && (member.get('CircleMember') as any);
        if (memberThrough && typeof memberThrough.update === 'function') {
            await memberThrough.update({ role, status });
        }
        res.json({ message: '更新成功' });
        return;
    } catch (error) {
        console.error('更新圈子成员失败:', error);
        res.status(500).json({ message: '更新圈子成员失败' });
    }
}; 